#include "Windows.h"
#include "Log.h"
#include "VolumeControl.h"

static VolumeController gVolumeController;

void DoShutdown(bool reboot)
{
	HANDLE token;
	TOKEN_PRIVILEGES privileges;

	OpenProcessToken(GetCurrentProcess(), TOKEN_ADJUST_PRIVILEGES | TOKEN_QUERY, &token);

	if (token)
	{
		LookupPrivilegeValue(NULL, SE_SHUTDOWN_NAME, &privileges.Privileges[0].Luid);
		privileges.PrivilegeCount = 1;
		privileges.Privileges[0].Attributes = SE_PRIVILEGE_ENABLED;
		AdjustTokenPrivileges(token, FALSE, &privileges, 0, NULL, 0);
	}

	InitiateSystemShutdown(NULL, NULL, 0, TRUE, reboot ? TRUE : FALSE);
}

extern "C"
{
	struct FVector
	{
		float x,y,z;
	};

	__declspec(dllexport) void LogInfo(wchar_t* channel, wchar_t* data)
	{
		Logger::Singleton().Log(data, LOG_Info, channel);
	}

	__declspec(dllexport) void LogWarn(wchar_t* channel, wchar_t* data)
	{		
		Logger::Singleton().Log(data, LOG_Warning, channel);
	}

	__declspec(dllexport) void LogError(wchar_t* channel, wchar_t* data)
	{		
		Logger::Singleton().Log(data, LOG_Error, channel);
	}

	__declspec(dllexport) float GetVolume()
	{		
		return gVolumeController.GetVolume();
	}

	__declspec(dllexport) void SetVolume(float volume)
	{		
		gVolumeController.SetVolume(volume);
	}

	__declspec(dllexport) void SystemShutdown()
	{		
		DoShutdown(false);		
	}

	__declspec(dllexport) void SystemReboot()
	{		
		DoShutdown(true);
	}
}


BOOL APIENTRY DllMain(
					__in  HINSTANCE hinstDLL,
					__in  DWORD fdwReason,
					__in  LPVOID lpvReserved
					)
{
	switch (fdwReason)
	{
	case DLL_PROCESS_ATTACH:
		{
			Logger::Singleton().Startup(hinstDLL);
			gVolumeController.Init();
			break;
		}
	case DLL_PROCESS_DETACH:
		{
			Logger::Singleton().Shutdown();
			break;
		}		
	}
	return TRUE;
}
